/*
 * @Author: yangrongxin
 * @Date: 2021-08-04 17:49:48
 * @LastEditors: yangrongxin
 * @LastEditTime: 2021-08-13 11:03:01
 */
import { useState, useEffect } from 'react';
import Taro from '@tarojs/taro';
import { View, Text } from '@tarojs/components';
import { placeOrder, pay } from '@/services/global';

const Payment = (props) => {
  const { orderId, measureTableId, wapperClassName, text, name, onClose } = props;

  const [isPayFinish, setIsPayFinish] = useState<boolean>(false);
  const [measureTableRecordId, setMeasureTableRecordId] = useState<string>('');

  useEffect(() => {
    setIsPayFinish(false);
  }, [measureTableId]);

  const payFn = (resOrderId: string) => {
    pay({
      orderId: resOrderId,
    }).then((payRes: any = {}) => {
      // 支付完成之后当前进入到开始答题模式
      const { measureTableRecordList = [] } = payRes;
      const recordItem = measureTableRecordList.find((fi: any) => fi.measureTableId === measureTableId);
      Taro.showToast({
        title: '购买完成！',
        icon: 'none',
      });
      setMeasureTableRecordId(recordItem.measureTableRecordId);
      setIsPayFinish(true);
      console.log('payRes', payRes);
    });
  };

  const placeAnOrder = () => {
    console.log('isPayFinish', isPayFinish);
    if (!isPayFinish) {
      // 未支付订单 进入下单流程
      // 待支付订单 直接进入支付流程
      if (!orderId) {
        placeOrder({
          measureTableId,
        }).then((res: any = {}) => {
          if (res.orderId) payFn(res.orderId);
          console.log('placeOrder', res);
        });
      } else {
        payFn(orderId);
      }
    } else {
      // 已经支付订单 点击进行开始答题
      onClose && onClose();
      Taro.navigateTo({
        url: `/EvaluationModule/pages/CheckboxAnwser/index?measureTableId=${measureTableId}&title=${name}&measureTableRecordId=${measureTableRecordId}`,
      });
    }
  };

  return (
    <View className={wapperClassName} onClick={placeAnOrder}>
      <Text>{isPayFinish ? '开始答题' : `${text}`}</Text>
    </View>
  );
};

export default Payment;
